# -*- coding: utf-8 -*-


# 进程池
from concurrent.futures import ProcessPoolExecutor
# 请求模块
import requests
import os
import re

# 准备请求头
head = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'}

# 获取数据
def Craw():
    # 向所有英雄的url发请求 得到heroid name
    url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2884684'

    # 打印响应数据
    res = requests.get(url, headers=head)
    # 获取的json格式数据转换成字典，通过字典key取值
    data = res.json()['hero']  # data是一个列表

    # 数据类型是列表  采取循环遍历
    lst = []
    for hero in data[:10]:
        # print(hero)
        heroId = hero['heroId']
        hero_name = hero['name']
        path = f'英雄图片/{hero_name}'
        if not os.path.exists(path):
            os.mkdir(path)
        # print(hero)
        # print(hero_name, heroId)
        # 组成英雄链接 图片链接都保存在单个英雄数据包当中 所以利用heroid进行一个循环处理
        hero_url = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{heroId}.js?ts=2884684'
        # 发请求，获取响应
        res2 = requests.get(hero_url, headers=head)
        hero_data = res2.json()['skins']
        for detail_hero in hero_data:
            # 获取图片链接
            mainImg = detail_hero['mainImg']  # 图片链接
            # 获取英雄名称  对应图片名称命名
            picture_name = detail_hero['name']  # 图片名字
            # 将获取到的数据存放到队列当中
            lst.append((mainImg, picture_name, path))
    return lst


# 保存数据
def get_img(data):
    mainImg, picture_name, path = data   # 元组
    picture_name = re.sub(r'[/\\?:："<>*]', '', picture_name)
    try:
        if mainImg:  # 有数据
            # 数据保存  urlretrieve(链接， 保存的路径)
            res = requests.get(mainImg, headers=head)
            with open(f'{path}/{picture_name}.jpg', 'wb') as f:
                f.write(res.content)
            # request.urlretrieve(mainImg, f'{path}/{picture_name}.jpg')
            print(f'{picture_name}下载成功')
    except Exception as e:
        print(e, mainImg)


# 进程池
if __name__ == '__main__':
    with ProcessPoolExecutor()as pool:
        future = pool.submit(Craw)  # mianImg picture_name path
        lst = future.result()  # 获取结果  [(),(),()]
        # 数据保存
        pool.map(get_img, lst)


